package com.hxx.widget.richtext.editor

import android.text.Editable
import android.text.Selection
import android.text.Spanned
import android.text.style.CharacterStyle
import android.text.style.ParagraphStyle

class EditorCharHistory(
    var oldChars: String = "",
    var replaceChars: String = "",
    var start: Int = 0,
    var oldSpans: List<StepSpanInfo> = arrayListOf(),
    var currentSpans: List<StepSpanInfo> = arrayListOf(),
) : EditorHistory {

    override fun redo(editor: Editable) {
        val count = oldChars.length
        editor.replace(start, start + count, replaceChars)

        val characterSpans = editor.getSpans(0, editor.length, CharacterStyle::class.java)
        val paragraphSpans = editor.getSpans(0, editor.length, ParagraphStyle::class.java)
        characterSpans.forEach {
            editor.removeSpan(it)
        }
        paragraphSpans.forEach {
            editor.removeSpan(it)
        }
        currentSpans.forEach {
            if (it.start >= 0 && it.end >= it.start) {
                editor.setSpan(it.span, it.start, it.end, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
            }
        }

        Selection.setSelection(editor, start + replaceChars.length)
    }

    override fun undo(editor: Editable) {
        val count = replaceChars.length
        editor.replace(start, start + count, oldChars)

        val characterSpans = editor.getSpans(0, editor.length, CharacterStyle::class.java)
        val paragraphSpans = editor.getSpans(0, editor.length, ParagraphStyle::class.java)
        characterSpans.forEach {
            editor.removeSpan(it)
        }
        paragraphSpans.forEach {
            editor.removeSpan(it)
        }
        oldSpans.forEach {
            editor.setSpan(it.span, it.start, it.end, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
        }

        Selection.setSelection(editor, start + oldChars.length)
    }
}